package com.nuckly.news.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.nuckly.news.data.News
import com.nuckly.news.databinding.ListItemNewsFeedBinding

class NewsFeedAdapter(private val onItemClick: (News) -> Unit) :
    ListAdapter<News, NewsFeedAdapter.ViewHolder>(NewsDiff()) {

    class NewsDiff: DiffUtil.ItemCallback<News>() {
        override fun areItemsTheSame(oldItem: News, newItem: News): Boolean {
            return oldItem.title == newItem.title
        }

        override fun areContentsTheSame(oldItem: News, newItem: News): Boolean {
            return oldItem == newItem
        }
    }

    class ViewHolder(private val binding: ListItemNewsFeedBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(news: News, onItemClick: (News) -> Unit) {
            binding.news = news
            binding.root.setOnClickListener {
                onItemClick(news)
            }
            binding.executePendingBindings()
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = ListItemNewsFeedBinding.inflate(layoutInflater, parent, false)
                return ViewHolder(binding)
            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder.from(parent)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val news = getItem(position)
        holder.bind(news, onItemClick)
    }

}